package com.example.controller;

import com.example.pojo.vo.PhotoUserID;
import com.example.tools.Result;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;

@Slf4j
@RestController
@RequestMapping("/faceRegistration")
public class FaceRegistrationController {

    public static final String API_KEY = "rhhCttgVdhBAByGyaEpkzK3G";
    public static final String SECRET_KEY = "MazQE6UhXk0Wg8xiHPwMD4SP6M6JWo2e";

    static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();

    @PostMapping("/addFace")
    public Result addFace(@org.springframework.web.bind.annotation.RequestBody PhotoUserID photoUserID) throws IOException, JSONException {
        MediaType mediaType = MediaType.parse("application/json");
        String photoData=photoUserID.getPhotoData();
        Integer userId = photoUserID.getUserId();
        System.out.println(userId);
        //base64Photo=base64Photo.substring(10,base64Photo.length()-2);
        //System.out.println(photoData);
        RequestBody body = RequestBody.create(mediaType, String.format("{\"group_id\":\"111\",\"image\":\"%s\",\"image_type\":\"BASE64\",\"user_id\":\"%s\"}", photoData, userId));
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rest/2.0/face/v3/faceset/user/add?access_token=" + getAccessToken())
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        System.out.println(response.body().string());
        return Result.success(response);
    }

    static String readFileContentAsBase64(String filePath) throws IOException {
        byte[] fileContent = Files.readAllBytes(Paths.get(filePath));
        return Base64.getEncoder().encodeToString(fileContent);
    }

    static String getFileContentAsBase64(String path, boolean urlEncode) throws IOException {
        byte[] b = Files.readAllBytes(Paths.get(path));
        String base64 = Base64.getEncoder().encodeToString(b);
        if (urlEncode) {
            base64 = URLEncoder.encode(base64, "utf-8");
        }
        return base64;
    }

    static String getAccessToken() throws IOException, JSONException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API_KEY + "&client_secret=" + SECRET_KEY);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token")
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        return new JSONObject(response.body().string()).getString("access_token");
    }
}